<template>
	<swiper class="home-swiper" :current="activeIndex" @change="change">
		<swiper-item v-for="(item,index) in tab" :key="index" class="swiper-item">
			<listItem :list="listCatchData[index]" @loadmore="loadmore" :load="load[index]"></listItem>
		</swiper-item>
	</swiper>
</template>

<script>
	import listItem from './list-item.vue'
	export default {
		data() {
			return {
				list: [],
				listCatchData: {},
				load: {},
				pageSize: 10
			};
		},
		props: {
			tab: {
				type: Array,
				default(){
					return []
				}
			},
			activeIndex: {
				type: Number,
				default: 0
			}
		},
		watch: {
			tab(newVal,oldVal){
				if(newVal.length === 0){
					return
				}else{
					this.listCatchData = {}
					this.load = {}
					this.getList(this.activeIndex)
				}
			}
		},
		created(){
			// this.getList(0)
			uni.$on('update_article',(e) => {
				if(e === 'follow'){
					this.listCatchData = {}
					this.load = {}
					this.getList(this.activeIndex)
				}
				
			})
		},
		methods: {
			change(e){
				this.$emit('change',e.detail.current)
				// 当数据不存在或长度为0的情况下才去请求数据
				if(!this.listCatchData[e.detail.current] || this.listCatchData[e.detail.current].length === 0){
					this.getList(e.detail.current)
				}	
			},
			getList(current){
				if(!this.load[current]){
					this.load[current] = {
						page: 1,
						loading: 'loading'
					}
				}
				this.$api.get_list({
						name: this.tab[current].name,
						page: this.load[current].page,
						pageSize: this.pageSize
					}).then(res => {
					const {data} = res
					// this.listCatchData[current] = data
					if(data.length === 0){
						let oldLoad = {}
						oldLoad.loading = 'noMore',
						oldLoad.page = this.load[current].page
						this.$set(this.load,current,oldLoad)
						//强制渲染页面
						this.$forceUpdate()
						return
					}
					let oldList = this.listCatchData[current] || []
					oldList.push(...data)
					//懒加载
					this.$set(this.listCatchData,current,oldList)
				})
			},
			loadmore(){
				if(this.load[this.activeIndex].loading === 'noMore'){
					return
				}
				this.load[this.activeIndex].page++
				this.getList(this.activeIndex)
			}
		},
		components: {
			listItem
		}
	}
</script>

<style lang="scss">
	.home-swiper{
		height: 100%;
		.swiper-item{
			height: 100%;
			overflow: hidden;
		}
		
	}
</style>
